package com.rzjm.api.netty.water.business.inhandler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.entity.DeviceWater;
import com.rzjm.api.entity.DeviceWaterOrder;
import com.rzjm.api.netty.water.NettyUtil;
import com.rzjm.api.netty.water.ResponseData;
import com.rzjm.api.netty.water.constant.ResultCodeEnum;
import com.rzjm.api.netty.water.entity.ReceiveData;
import com.rzjm.api.service.IDeviceWaterMessagesService;
import com.rzjm.api.service.IDeviceWaterOrderService;
import com.rzjm.api.service.IDeviceWaterService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;

import static com.rzjm.api.netty.water.constant.SendRtEnum.SEND_RT_9;
import static com.rzjm.api.util.DateUtils.localDateTimeStartToSecond;

/**
 *  刷卡后的出水  绿色按钮 请求
 * @author Mr.Zhou
 * @Description:
 * @date 2025/3/17 9:27
 */
@Component
public class Receive9InHandler implements InHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(Receive9InHandler.class);
    @Autowired
    private IDeviceWaterService devicesService;
    @Autowired
    private IDeviceWaterMessagesService deviceMessagesService;
    @Autowired
    private IDeviceWaterOrderService waterOrderService;


    @Override
    public void handler(ChannelHandlerContext ctx, ReceiveData receiveData) {
        //保存Channel
        NettyUtil.addChannel(ctx, receiveData.getId());
        // 保存上报数据日志
        Optional.ofNullable(getMessage(receiveData))
                .ifPresent(message -> deviceMessagesService.save(message));

        //设备应答消息
        String tag = receiveData.getV2() != null ? receiveData.getV2() : receiveData.getTag()+"";
        if (tag != null && NettyUtil.SYNC_RESPONSEDATA_MAP.containsKey(tag)) {
            ResponseData responseData = NettyUtil.SYNC_RESPONSEDATA_MAP.get(tag);
            if (responseData != null) {
                String message = JSONUtil.toJsonStr(receiveData);
                responseData.setCode(ResultCodeEnum.OK.getCode());
                responseData.setMsg(ResultCodeEnum.OK.getDescription());
                responseData.setReceiveDataStr(message);
                responseData.setReceiveData(receiveData);
                responseData.getPromise().setSuccess();
            }
        } else {
            //同步消息或同步非阻塞消息，暂时没有处理逻辑
        }

        DeviceWater deviceWater = devicesService.findById(receiveData.getId());
        //回复消息
        String replyData = requestData(deviceWater, receiveData);
        if (StrUtil.isNotEmpty(replyData)) {
            reply(replyData, receiveData.getId());
        }
    }

    /**
     * 開始出水
     * @param deviceWater
     * @param receiveData
     * @return
     */
    private String requestData(DeviceWater deviceWater, ReceiveData receiveData) {
//        DeviceWater device = devicesService.findById(id);
//        if (device == null) {
//            return "{\"rt\":5,\"v1\":4}";
//        }
        System.out.println("开始出水（按绿色按钮）数据上报请求：" + JSONUtil.toJsonStr(receiveData));
        String replyData;
        // 当日开始时间的总秒数
        long startSecond = localDateTimeStartToSecond();
        JSONObject obj = JSONUtil.createObj();

        obj = JSONUtil.createObj();
        obj.set("rt", SEND_RT_9.getRt());
        obj.set("v1", receiveData.getV1());

        QueryWrapper<DeviceWaterOrder> qw = new QueryWrapper<>();
        qw.eq("order_no", receiveData.getV1());
        qw.last("limit 1");
        DeviceWaterOrder waterOrder = waterOrderService.getOne(qw);
        if(waterOrder == null){
            return "{\"rt\":9,\"v1\":1}";
        }

        waterOrder.setStatus(2);
        waterOrder.setPayTime(new Date());
        boolean bl = waterOrderService.updateById(waterOrder);
        if(bl){
            obj.set("v1", 0);
        }else{
            obj.set("v1", 2);
        }

        replyData = JSONUtil.toJsonStr(obj);
        return replyData;
    }

}
